﻿using System;
using ProjectDanmaku.Util;
using UnityEngine;
using UnityEngine.UI;
using Random = System.Random;

namespace ProjectDanmaku.Entity.SubLayer.EnemyBullet
{
    public class TestBulletData : EntityData
    {
        
    }
    
    public class TestBulletLayer : EntitySubLayer
    {
        [SerializeField] private Slider propSlider;
        [SerializeField] private Slider countSlider;
        [SerializeField] private Text propText;
        [SerializeField] private Text countText;
        
        private readonly Random _random = new Random();

        [SerializeField] private Sprite bulletSprite;
        
        private Mesh _mesh;
        
        protected override void Awake()
        {
            base.Awake();
            
            _mesh = MeshUtility.SpriteToMesh(bulletSprite);
            
            Material.SetTexture("_MainTex", bulletSprite.texture);
        }

        public override Type GetEntityDataType()
        {
            return typeof(TestBulletData);
        }

        protected override void EntityLogicTick(EntityData data)
        {
            data.Position += data.Velocity * Time.deltaTime;

            if (CheckOutOfScreen(data.Position))
            {
                data.Destroyed = true;
                data.Active = false;
            }
        }

        protected override void EntityPhysicsTick(EntityData data)
        {
            
        }

        protected override void EntityLateTick(EntityData data)
        {
            
        }

        protected override void EntityInit(EntityData data)
        {
            
        }

        public override Mesh GetSpriteMesh()
        {
            return _mesh;
        }

        private void AddEntityRandomly(Vector2 vec)
        {
            var vDotU = Vector2.Dot(vec, Vector2.up);
            var right = Mathf.Sign(Vector2.Dot(vec, Vector2.right));

            var rad = right * Mathf.Acos(vDotU) + Mathf.PI / 2f;
            
            AddEntity(new TestBulletData()
            {
                Velocity = vec,
                RotateZ = rad
            });
        }

        private void AddEntityRandomly()
        {
            AddEntityRandomly(new Vector2(_random.Next(-100, 100), _random.Next(-100, 100)).normalized);
        }

        private void Update()
        {
            if (_random.Next(0, 100) < propSlider.value)
            {
                for (int i = 0; i < countSlider.value; ++i)
                {
                    AddEntityRandomly();
                }
            }
            
            propText.text = propSlider.value.ToString();
            countText.text = countSlider.value.ToString();
        }
    }
}